//
//  ARTWatchSettingController.m
//  ChartsDemo
//
//  Created by yunda on 2022/1/18.
//

#import "ARTWatchSettingController.h"
#import "ARTSleepSettingCell.h"
#import "ARTSleepSetPopView.h"
#import "ARTWathDataAnalysis.h"

@interface ARTWatchSettingController ()<UITableViewDelegate,UITableViewDataSource>{
    NSData *_currentData;
    Byte *_currentBytes;
}

@property (strong, nonatomic)  UITableView *tableView;

@property (strong, nonatomic)  ARTWathDataAnalysis *dataAnalysis;

@end

@implementation ARTWatchSettingController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = FYLocalizedString(@"sleep_watch_settings", @"");
    
//    Byte temp[] = {0xfe, 0x5a, 0x0f, 0x1b, 0x02, 0x00, 0x1e, 0x00, 0x01, 0x5e, 0x3c, 0x64, 0x02, 0x01, 0x3d};
//    _currentData = [NSData dataWithBytes:temp length:15];
//    _currentBytes = (Byte *)[_currentData bytes];
    [self.view addSubview:self.tableView];
    
    [self babyDelegate];
}

- (void)babyDelegate{
    _baby = ARTSingleShare.baby;
    _currentPeripheral = ARTSingleShare.currentPeripheral;
    _writeCharacteristic = ARTSingleShare.writeCharacteristic;
    _notifyCharacteristic = ARTSingleShare.currentCharacteristic;
    if (!_baby || !_currentPeripheral || !_notifyCharacteristic || !_writeCharacteristic) {
        return;
    }
    J_WeakSelf(self)
    [_baby notify:_currentPeripheral characteristic:_notifyCharacteristic block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
        J_StrongSelf(self)
//        NSLog(@"-收到设置-%@",[ASFHConverter convert_16String_with_16Data:characteristics.value]);
        [self.dataAnalysis analysisData:characteristics.value];
    }];
        
    [self.baby setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        J_StrongSelf(self);
        NSLog(@"==断开链接==");
        [QMUITips showWithText:FYLocalizedString(@"oxygen_off_line", @"")];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    // 获取设置状态
//    [self getSettingData];
    if (ARTSingleShare.currentSettingData) {
        [self configureData:ARTSingleShare.currentSettingData];
    }
}

#pragma mark--UITableViewDelegate && UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 12;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ARTSleepSettingCell *cell = [ARTSleepSettingCell cellWithTableView:tableView];
    cell.contentLabel.hidden = NO;
    cell.nextImageView.hidden = NO;
    cell.switchButton.hidden = YES;
    if (indexPath.row == 0){
        cell.titleLabel.text = FYLocalizedString(@"sleep_watch_user_id", @"");
        NSInteger value = [self valueWithIndex:5];
        cell.contentLabel.text = [NSString stringWithFormat:@"0%@",@(value+1)];
    }else if (indexPath.row == 1){
        cell.titleLabel.text = FYLocalizedString(@"sleep_watch_user_age", @"");
        NSInteger value = [self valueWithIndex:6];
        cell.contentLabel.text = [NSString stringWithFormat:@"%@",@(value)];
    }else if (indexPath.row == 2){
        cell.titleLabel.text = FYLocalizedString(@"sleep_watch_user_sex", @"");
        NSInteger value = [self valueWithIndex:7];
        if (value == 0) {
            cell.contentLabel.text = FYLocalizedString(@"sleep_watch_man", @"");
        }else{
            cell.contentLabel.text = FYLocalizedString(@"sleep_watch_woman", @"");
        }
    }
    else if (indexPath.row == 3){
        // 血氧报警提醒
        cell.titleLabel.text = FYLocalizedString(@"sleep_watch_alarm_sp", @"");
        cell.contentLabel.hidden = YES;
        cell.nextImageView.hidden = YES;
        cell.switchButton.hidden = NO;
//        NSInteger value = [self valueWithIndex:8];
        if (_currentData.length > 13) {
            cell.switchButton.on = ((_currentBytes[8]&1) == 1);
        }else{
            cell.switchButton.on = NO;
        }
        [cell.switchButton addTarget:self action:@selector(oxSwitchAction:) forControlEvents:UIControlEventValueChanged];
    }
    else if (indexPath.row == 4){
        cell.titleLabel.text = FYLocalizedString(@"sleep_watch_alarm_lowspo", @"");
        NSInteger value = [self valueWithIndex:9];
        cell.contentLabel.text = [NSString stringWithFormat:@"%@",@(value)];
    }
    else if (indexPath.row == 5){
        // 心率报警提醒
        cell.titleLabel.text = FYLocalizedString(@"sleep_watch_alarm_pr", @"");
        cell.contentLabel.hidden = YES;
        cell.nextImageView.hidden = YES;
        cell.switchButton.hidden = NO;
//        NSInteger value = [self valueWithIndex:8];
        if (_currentData.length > 13) {
            cell.switchButton.on = ((_currentBytes[8]&2) == 2);
        }else{
            cell.switchButton.on = NO;
        }
        [cell.switchButton addTarget:self action:@selector(prSwitchAction:) forControlEvents:UIControlEventValueChanged];
    }
    else if (indexPath.row == 6){
        cell.titleLabel.text = FYLocalizedString(@"sleep_watch_alarm_lowpr", @"");
        NSInteger value = [self valueWithIndex:10];
        cell.contentLabel.text = [NSString stringWithFormat:@"%@",@(value)];
    }else if (indexPath.row == 7){
        cell.titleLabel.text = FYLocalizedString(@"sleep_watch_alarm_highpr", @"");
        NSInteger value = [self valueWithIndex:11];
        cell.contentLabel.text = [NSString stringWithFormat:@"%@",@(value)];
    }else if (indexPath.row == 8){
        cell.titleLabel.text = FYLocalizedString(@"sleep_watch_brightness", @"");
        NSInteger value = [self valueWithIndex:12];
        cell.contentLabel.text = [NSString stringWithFormat:@"%@",@(value+1)];
    }else if (indexPath.row == 9){
        cell.titleLabel.text = FYLocalizedString(@"sleep_watch_backlight_time", @"");
        NSInteger value = [self valueWithIndex:13];
        if (value == 0) {
            cell.contentLabel.text = @"10s";
        }else if (value == 1){
            cell.contentLabel.text = @"30s";
        }else if (value == 2){
            cell.contentLabel.text = @"60s";
        }else if (value == 3){
            cell.contentLabel.text = @"120s";
        }else if (value == 4){
            cell.contentLabel.text = FYLocalizedString(@"sleep_watch_light", @"");
        }
    }else if (indexPath.row == 10){
        cell.titleLabel.text = FYLocalizedString(@"open_usb", @"");
        cell.contentLabel.hidden = YES;
        cell.nextImageView.hidden = YES;
    }else if (indexPath.row == 11){
        cell.titleLabel.text = FYLocalizedString(@"sleep_watch_init", @"");
        cell.contentLabel.hidden = YES;
        cell.nextImageView.hidden = YES;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        // 用户ID
        NSNumber *version = J_UserDefault_GetObjectForKey(ART_Storage_WatchVersion);
        if (version.integerValue < 113) {
            [QMUITips showWithText:FYLocalizedString(@"sleep_watch_firmware", @"")];
            return;
        }
        
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 0; i <= 1; i++) {
            ARTSleepSetModel *model = [[ARTSleepSetModel alloc]initWithTitle:@(i+1).stringValue value:@(i).stringValue];
            [array addObject:model];
        }
        ARTSleepSetPopView *view = [[ARTSleepSetPopView alloc]init];
        view.defaultValue = [self valueWithIndex:5];
        view.dataSourceArray = array;
        view.okBlock = ^(ARTSleepSetModel * _Nonnull model) {
            NSString *value_16 = [ASFHConverter convert_16_with_10:model.value];
            NSData *data_16 = [ASFHConverter convert_16Data_with_16String:value_16];
            Byte *bytes_16 = (Byte *)[data_16 bytes];
            [self sendSetting:bytes_16[0] index:5];
        };
        [view show];
    }else if (indexPath.row == 1){
        // 用户年龄
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 1; i <= 100; i++) {
            ARTSleepSetModel *model = [[ARTSleepSetModel alloc]initWithTitle:@(i).stringValue value:@(i).stringValue];
            [array addObject:model];
        }
        ARTSleepSetPopView *view = [[ARTSleepSetPopView alloc]init];
        view.defaultValue = [self valueWithIndex:6];
        view.dataSourceArray = array;
        view.okBlock = ^(ARTSleepSetModel * _Nonnull model) {
            NSString *value_16 = [ASFHConverter convert_16_with_10:model.value];
            NSData *data_16 = [ASFHConverter convert_16Data_with_16String:value_16];
            Byte *bytes_16 = (Byte *)[data_16 bytes];
            [self sendSetting:bytes_16[0] index:6];
        };
        [view show];
    }else if (indexPath.row == 2){
        // 用户性别
        NSMutableArray *array = [NSMutableArray array];
        ARTSleepSetModel *model1 = [[ARTSleepSetModel alloc]initWithTitle:FYLocalizedString(@"sleep_watch_man", @"") value:@"0"];
        [array addObject:model1];
        ARTSleepSetModel *model2 = [[ARTSleepSetModel alloc]initWithTitle:FYLocalizedString(@"sleep_watch_woman", @"") value:@"1"];
        [array addObject:model2];
        ARTSleepSetPopView *view = [[ARTSleepSetPopView alloc]init];
        view.defaultValue = [self valueWithIndex:7];
        view.dataSourceArray = array;
        view.okBlock = ^(ARTSleepSetModel * _Nonnull model) {
            NSString *value_16 = [ASFHConverter convert_16_with_10:model.value];
            NSData *data_16 = [ASFHConverter convert_16Data_with_16String:value_16];
            Byte *bytes_16 = (Byte *)[data_16 bytes];
            [self sendSetting:bytes_16[0] index:7];
        };
        [view show];
    }else if (indexPath.row == 3){
        // 血氧报警提醒
    }else if (indexPath.row == 4){
        // 最低血氧报警值设置
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 70; i <= 94; i++) {
            ARTSleepSetModel *model = [[ARTSleepSetModel alloc]initWithTitle:@(i).stringValue value:@(i).stringValue];
            [array addObject:model];
        }
        ARTSleepSetPopView *view = [[ARTSleepSetPopView alloc]init];
        view.defaultValue = [self valueWithIndex:9];
        view.dataSourceArray = array;
        view.okBlock = ^(ARTSleepSetModel * _Nonnull model) {
            NSString *value_16 = [ASFHConverter convert_16_with_10:model.value];
            NSData *data_16 = [ASFHConverter convert_16Data_with_16String:value_16];
            Byte *bytes_16 = (Byte *)[data_16 bytes];
            [self sendSetting:bytes_16[0] index:9];
        };
        [view show];
    }else if (indexPath.row == 5){
        // 心率报警提醒
    }
    else if (indexPath.row == 6){
        // 最低脉率报警值设置
        NSMutableArray *array = [NSMutableArray array];
        NSInteger max = MIN([self valueWithIndex:11], 250);
        for (int i = 25; i < max; i++) {
            ARTSleepSetModel *model = [[ARTSleepSetModel alloc]initWithTitle:@(i).stringValue value:@(i).stringValue];
            [array addObject:model];
        }
        ARTSleepSetPopView *view = [[ARTSleepSetPopView alloc]init];
        view.defaultValue = [self valueWithIndex:10];
        view.dataSourceArray = array;
        view.okBlock = ^(ARTSleepSetModel * _Nonnull model) {
            NSString *value_16 = [ASFHConverter convert_16_with_10:model.value];
            NSData *data_16 = [ASFHConverter convert_16Data_with_16String:value_16];
            Byte *bytes_16 = (Byte *)[data_16 bytes];
            [self sendSetting:bytes_16[0] index:10];
        };
        [view show];
    }else if (indexPath.row == 7){
        // 最高脉率报警值设置
        NSMutableArray *array = [NSMutableArray array];
        NSInteger min = MAX([self valueWithIndex:10], 25);
        for (long i = min+1; i <= 250; i++) {
            ARTSleepSetModel *model = [[ARTSleepSetModel alloc]initWithTitle:@(i).stringValue value:@(i).stringValue];
            [array addObject:model];
        }
        ARTSleepSetPopView *view = [[ARTSleepSetPopView alloc]init];
        view.defaultValue = [self valueWithIndex:11];
        view.dataSourceArray = array;
        view.okBlock = ^(ARTSleepSetModel * _Nonnull model) {
            NSString *value_16 = [ASFHConverter convert_16_with_10:model.value];
            NSData *data_16 = [ASFHConverter convert_16Data_with_16String:value_16];
            Byte *bytes_16 = (Byte *)[data_16 bytes];
            [self sendSetting:bytes_16[0] index:11];
        };
        [view show];
    }else if (indexPath.row == 8){
        // 屏幕亮度设置
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 0; i <= 4; i++) {
            ARTSleepSetModel *model = [[ARTSleepSetModel alloc]initWithTitle:@(i+1).stringValue value:@(i).stringValue];
            [array addObject:model];
        }
        ARTSleepSetPopView *view = [[ARTSleepSetPopView alloc]init];
        view.defaultValue = [self valueWithIndex:12];
        view.dataSourceArray = array;
        view.okBlock = ^(ARTSleepSetModel * _Nonnull model) {
            NSString *value_16 = [ASFHConverter convert_16_with_10:model.value];
            NSData *data_16 = [ASFHConverter convert_16Data_with_16String:value_16];
            Byte *bytes_16 = (Byte *)[data_16 bytes];
            [self sendSetting:bytes_16[0] index:12];
        };
        [view show];
    }else if (indexPath.row == 9){
        // 背光时间设置
        NSMutableArray *array = [NSMutableArray array];
        ARTSleepSetModel *model1 = [[ARTSleepSetModel alloc]initWithTitle:@"10s" value:@"0"];
        [array addObject:model1];
        ARTSleepSetModel *model2 = [[ARTSleepSetModel alloc]initWithTitle:@"30s" value:@"1"];
        [array addObject:model2];
        ARTSleepSetModel *model3 = [[ARTSleepSetModel alloc]initWithTitle:@"60s" value:@"2"];
        [array addObject:model3];
        ARTSleepSetModel *model4 = [[ARTSleepSetModel alloc]initWithTitle:@"120s" value:@"3"];
        [array addObject:model4];
        ARTSleepSetModel *model5 = [[ARTSleepSetModel alloc]initWithTitle:FYLocalizedString(@"sleep_watch_light", @"") value:@"4"];
        [array addObject:model5];
        ARTSleepSetPopView *view = [[ARTSleepSetPopView alloc]init];
        view.defaultValue = [self valueWithIndex:13];
        view.dataSourceArray = array;
        view.okBlock = ^(ARTSleepSetModel * _Nonnull model) {
            NSString *value_16 = [ASFHConverter convert_16_with_10:model.value];
            NSData *data_16 = [ASFHConverter convert_16Data_with_16String:value_16];
            Byte *bytes_16 = (Byte *)[data_16 bytes];
            [self sendSetting:bytes_16[0] index:13];
        };
        [view show];
    }else if (indexPath.row == 10){
        // 打开usb
        Byte temp[] = {0xFE,0x5A,0x07,0x1B,03,0,25};
        NSData *data = [NSData dataWithBytes:temp length:7];
        NSLog(@"打开=%@",data);
        [self.currentPeripheral writeValue:data forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
    }else if (indexPath.row == 11){
        // 恢复出厂设置
        Byte temp[] = {0xfe, 0x5a, 0x05, 0x1b, 0x01};
        NSData *data = [NSData dataWithBytes:temp length:5];
        [self.currentPeripheral writeValue:data forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
    }
}

- (void)oxSwitchAction:(UISwitch *)sender{
    if (((_currentBytes[8]&1) == 1)) {
        Byte byte = _currentBytes[8]&~(1 << 0);
        [self sendSetting:byte index:8];
    }else{
        Byte byte = _currentBytes[8] | (1 << 0);
        [self sendSetting:byte index:8];
    }
//    NSString *value_16 = [ASFHConverter convert_16_with_10:@(sender.on).stringValue];
//    NSData *data_16 = [ASFHConverter convert_16Data_with_16String:value_16];
//    Byte *bytes_16 = (Byte *)[data_16 bytes];
//    [self sendSetting:bytes_16[0] index:8];
}

- (void)prSwitchAction:(UISwitch *)sender{
    if (((_currentBytes[8]&2) == 2)) {
        Byte byte = _currentBytes[8]&~(1 << 1);
        [self sendSetting:byte index:8];
    }else{
        Byte byte = _currentBytes[8] | (1 << 1);
        [self sendSetting:byte index:8];
    }
//    NSString *value_16 = [ASFHConverter convert_16_with_10:@(sender.on).stringValue];
//    NSData *data_16 = [ASFHConverter convert_16Data_with_16String:value_16];
//    Byte *bytes_16 = (Byte *)[data_16 bytes];
//    [self sendSetting:bytes_16[0] index:8];
}

- (void)sendSetting:(Byte)byte index:(int)index{
    Byte *bufferBytes = (Byte *)malloc(14);
    Byte *recBytes = (Byte *)malloc(14);
    for (int i = 0; i < _currentData.length; i++) {
        if (i == index) {
            bufferBytes[i] = byte;
            recBytes[i] = byte;
        }else if (i == 4){
            bufferBytes[i] = 0x00;
            recBytes[i] = 0x02;
        }else{
            bufferBytes[i] = _currentBytes[i];
            recBytes[i] = _currentBytes[i];
        }
    }
    NSData *data = [NSData dataWithBytes:bufferBytes length:14];
    NSData *recData = [NSData dataWithBytes:recBytes length:14];
    [self.currentPeripheral writeValue:data forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
    [self.currentPeripheral writeValue:data forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
    free(bufferBytes);
    free(recBytes);
    NSLog(@"==send setting data=%@",[ASFHConverter convert_16String_with_16Data:data]);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self getSettingData];
//        [self configureData:recData];
    });
}

- (void)getSettingData{
    Byte byte[] = {0xFE,0x5A,0x05,0x1B,0x02};
    NSData *data = [NSData dataWithBytes:byte length:5];
    [_currentPeripheral writeValue:data forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

- (NSInteger)valueWithIndex:(NSInteger)index{
    if (_currentData.length > 13) {
        NSInteger value = _currentBytes[index]&0xFF;
        return value;
    }
    return 0;
}

- (void)configureData:(NSData *)datas{
    Byte *bytes = (Byte *)[datas bytes];
    if ((bytes[4] == 0x02 || bytes[4] == 0x00) && datas.length > 13) {
//    if (bytes[4] == 0x02 && datas.length > 13) {
        self->_currentBytes = bytes;
        self->_currentData = datas;
        [self.tableView reloadData];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark--GETTER
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 46;
    }
    return _tableView;
}

- (ARTWathDataAnalysis *)dataAnalysis{
    if (!_dataAnalysis) {
        ARTWathDataAnalysis *analysis = [[ARTWathDataAnalysis alloc]init];
        analysis.call_0x1B_back = ^(NSData * _Nullable datas) {
            [self configureData:datas];
        };
        _dataAnalysis = analysis;
    }
    return _dataAnalysis;
}

@end
